<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Modules Mixins: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby modules,ruby mixins,ruby study notes,free ruby programming guide,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/modules_mixins.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Ruby Learning site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Modules Mixins</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/object_serialization.html">&lt;Object Serialization | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_self.html">Self &gt;</a>
                  </strong>
                </p>

                <p>Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Modules are defined much like classes are, but the <strong>module</strong> keyword is used in place of the <strong>class</strong> keyword. <em>Unlike classes, you cannot create objects based on modules nor can you subclass them</em>; instead, you specify that you want the functionality of a particular module to be added to the functionality of a class, or of a specific object. Modules stand alone; there is no "module hierarchy" of inheritance. Modules is a good place to collect all your constants in a central location.</p>

                <p>Modules serve two purposes:</p>

                <ul>
                  <li>First they act as <em>namespace</em>, letting you define methods whose names will not clash with those defined elsewhere. The examples <strong>p058mytrig.rb, p059mymoral.rb, p060usemodule.rb</strong> illustrates this.</li>
                </ul>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p058mytrig.rb
                module Trig
                  PI = 3.1416
                  # class methods
                  def Trig.sin(x)
                    # ...
                  end
                  def Trig.cos(x)
                    # ...
                  end
                end

                # p059mymoral.rb
                module Moral
                  VERY_BAD = 0
                  BAD         = 1
                  def Moral.sin(badness)
                    # ...
                  end
                end

                # p060usemodule.rb
                require_relative 'p058mytrig'
                require_relative 'p059mymoral'
                Trig.sin(Trig::PI/4)
                Moral.sin(Moral::VERY_BAD)
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <ul>
                  <li>Second, they allow you to share functionality between classes - if a class mixes in a module, that module's instance methods become available as if they had been defined in the class. They get <em>mixed in</em>. The program <strong>p061mixins.rb</strong> illustrates this.</li>
                </ul>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p061mixins.rb
                module D
                  def initialize(name)
                    @name =name
                  end
                  def to_s
                    @name
                  end
                end

                module Debug
                  include D
                  # Methods that act as queries are often
                  # named with a trailing ?
                  def who_am_i?
                    "#{self.class.name} (\##{self.object_id}): #{self.to_s}"
                  end
                end

                class Phonograph
                  # the include statement simply makes a reference to a named module
                  # If that module is in a separate file, use require to drag the file in
                  # before using include
                  include Debug
                  # ...
                end

                class EightTrack
                  include Debug
                  # ...
                end

                ph = Phonograph.new("West End Blues")
                et = EightTrack.new("Real Pillow")
                puts ph.who_am_i?
                puts et.who_am_i?
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note">Observe how we use <strong>require</strong> or <strong>load</strong>. <strong>require</strong> and <strong>load</strong> take strings as their arguments.<br /><br /><b>require 'motorcycle'</b> or <b>load 'motorcycle.rb'</b><br /><br /><strong>include</strong> takes the name of a module, in the form of a constant, as in <b>include Stuff</b>.<br /><br />The <strong>include</strong> method accepts any number of <strong>Module</strong> objects to mix in:<br /><strong>include Enumerable, Comparable</strong><br /><br />Although every class is a module, the <strong>include</strong> method does not allow a class to be included within another class.</p>

                <p>Some more examples:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                #  p062stuff.rb
                #  A module may contain constants, methods and classes.
                #  No instances

                module Stuff
                  C = 10
                  def Stuff.m(x)  # prefix with the module name for a class method
                    C*x
                  end
                  def p(x)        # an instance method, mixin for other classes
                    C + x
                  end
                  class T
                    @t = 2
                  end
                end
                puts Stuff::C     # Stuff namespace
                puts Stuff.m(3)   # like a class method
                x = Stuff::T.new
                # uninitialized constant error, if you try the following
                # puts C

                #------------

                # p063stuffusage.rb
                require_relative 'p062stuff'     # loads Stuff module from Stuff.rb
                                    # $: is a system variable -- contains the path for loads
                class D
                  include Stuff     # refers to the loaded module
                  puts Stuff.m(4)
                end

                d = D.new
                puts d.p(5)         # method p from Stuff
                puts $:             # array of folders to search for load
                $: &lt;&lt; "c:/"         # add a folder to the load path
                puts $:
                puts Stuff.m(5)     # Stuff class methods not called from D object
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note">Remember that you can mix in more than one module in a class. However, a class cannot inherit from more than one class. Class names tend to be nouns, while module names are often adjectives.</p>

                <p class="post-note"><strong>IN RAILS</strong>: The Rails source code makes heavy use of modules, in particular the technique of reopening the definition bodies of both classes and modules.</p>
                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/titles/ruby3/programming-ruby-3">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/object_serialization.html">&lt;Object Serialization | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_self.html">Self &gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">

            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>
<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->

</body>
</html>
